import {defineStore} from "pinia";
import {reqLogin, reqUserInfo} from "@/api/user";
import {loginForm} from "@/api/user/type";
import {GET_TOKEN, SET_TOKEN, REMOVE_TOKEN} from "@/utils/token";
import {UserState} from "@/store/modules/types/type";
import {constantRoutes} from '@/router/routes'

let useUserStore = defineStore("user", {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            // 仓库存储生成菜单需要数组(路由)
            menuRoutes: constantRoutes,
            avatar: '',
            username: ''
        }
    },
    actions: {
        async userLogin(loginForm: loginForm) {
            // 登录请求
            let result = await reqLogin(loginForm);
            if (result.code == 200) {
                this.token = (result.data.token as string);
                SET_TOKEN(result.data.token);
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async getUserInfo() {
            // 获取用户信息
            let result = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data.username
                this.avatar = result.data.avatar
                return Promise.resolve()
            }else {
                return Promise.reject(new Error(result.message))
            }
        },
        logout() {
            REMOVE_TOKEN()
            this.token = ''
            this.username = ''
            this.avatar = ''
        }
    },
    getters: {}
})

export default useUserStore